﻿using Joz.RabbitMQClient;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Joz.Consumer
{
    public class TaskManagerService
    {
        //程序集名称（有固定的任务项目使用）
        private static string assemblyName = ConfigurationManager.AppSettings["assemblyName"];
        //前缀名称和程序集一直，后续需要和队列名称拼接
        private static string strongClassName = ConfigurationManager.AppSettings["assemblyName"];
        public void Start()
        {
            Listening();
        }

        public void Stop()
        {
            RabbitMqClient.Instance.Dispose();
        }

        private void Listening()
        {
            RabbitMqClient.Instance.ActionEventMessage += mqClient_ActionEventMessage;
            RabbitMqClient.Instance.OnListening();
        }

        private void mqClient_ActionEventMessage(EventMessageResult result)
        {
            try
            {
                //消息标记
                if (result.EventMessageBytes.EventMessageMarkcode == "") throw new Exception("消息标记为空,对列名为：" + result.RoutingKey);
                Assembly assembly = Assembly.Load(assemblyName);
                object jiafaObj = assembly.CreateInstance(strongClassName + "." + result.RoutingKey.Split('_')[0]);
                if (jiafaObj == null) throw new Exception("程序集映射失败：队列名为：" + result.RoutingKey);

                Type objType = jiafaObj.GetType();
                //根据函数名称创建方法元数据
                MethodInfo jiSuanMethod = objType.GetMethod(result.RoutingKey.Split('_')[1]);
                if (jiSuanMethod == null) throw new Exception("未在程序集中找到方法：队列名为：" + result.RoutingKey);
                //执行函数，以及获取函数返回值，//没参数用new object[] {}或 null 有参数用 new object[] {1,"str"} 
                object jiSuanReturn = jiSuanMethod.Invoke(jiafaObj, new object[] { result.MessageBytes });
                //对返回值jiSuanReturn进行处理，是否处理成功
                CommonCmdResult cmd = jiSuanReturn as CommonCmdResult;
                if (cmd.Flag)
                    result.IsOperationOk = true; //处理成功
                else
                    LogHelper.WriteErrorLog(cmd.Msg);
            }
            catch (Exception ex)
            {
                result.IsOperationOk = false;
                LogHelper.WriteErrorLog(ex.ToString());
            }
        }
    }
}
